﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;

namespace Enough.Converter
{
    public class CollectionSizeToBooleanConverter : IValueConverter
    {
        public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool reverse = "reverse".Equals(parameter);
            int requiredCollectionSize = 0;
            if (!reverse && parameter != null)
            {
                try
                {
                    requiredCollectionSize = int.Parse(parameter.ToString());
                }
                catch (Exception)
                {
                }
            }
            bool meetsRequiredCollectionSize;
            if (value is ICollection)
            {
                meetsRequiredCollectionSize = ((ICollection)value).Count == requiredCollectionSize;
            }
            else if (value is IEnumerable)
            {
                IEnumerator enumerator = ((IEnumerable)value).GetEnumerator();
                int size = 0;
                while (enumerator.MoveNext())
                {
                    size++;
                    if (size > requiredCollectionSize)
                    {
                        break;
                    }
                }
                meetsRequiredCollectionSize = (size == requiredCollectionSize);
            }
            else
            {
                meetsRequiredCollectionSize = false;
            }
            if (reverse)
            {
                meetsRequiredCollectionSize = !meetsRequiredCollectionSize;
            }
            return meetsRequiredCollectionSize;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
